let _Vue = null;
export default class VueRouter {
    static install(Vue) {
        if (VueRouter.install.installed) {
            return
        }
        VueRouter.install.installed = true;
        _Vue = Vue;
        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }
    constructor(options) {
        this.options = options;
        this.routerMap = {};
        this.data = _Vue.observable({
            current: '/'
        })
        console.log(options, 'xxx')
    }
    init() {
        this.createRouterMap();
        this.initComponent(_Vue);
        this.initEvent()
    }
    createRouterMap() {
        console.log(this)
        this.options.routes.forEach(route => {
            this.routerMap[route.path] = route.component;
        });
    }
    initComponent(Vue) {
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h) {
                return h('a', {
                    attrs: {
                        href: '#' + this.to,
                    },
                    on: {
                        click: (e) => {
                            //hash处理
                            window.location.hash = '#' + this.to;
                             //history
                            //  history.pushState({},'',this.to)
                            this.$router.data.current = this.to;
                            e.preventDefault()
                        }
                    },
                }, [this.$slots.default])
            }
        })
        const self = this;
        Vue.component('router-view', {
            props: {

            },
            render(h) {
                const component = self.routerMap[self.data.current]
                return h(component)
            }
        })

    }
    initEvent() {
        // window.addEventListener('popstate', () => {
        //     this.data.current = window.location.pathname;
        // })
        window.addEventListener('hashchange', () => {
            console.log(window.location)
            this.data.current = window.location.hash.substr(1)
        })
    }
}